package network.UDP;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;

    private String serveIp = "";

    private int servePort = 0;

    public UdpEchoClient(String ip, int port) throws SocketException {
        socket = new DatagramSocket();
        //  记录对应端的 ip 和 port
        serveIp = ip;
        servePort = port;
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            // 1. 从控制台读数据，作为请求
            System.out.println("->");
            String request = scanner.next();
            // 2. 把请求内容构造成 DatagramPacket 对象，发给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(serveIp), servePort);
            socket.send(requestPacket);
            // 3. 读取服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            // 4. 把相响应换为字符串
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
